import request from '@/utils/request'
import { defineStore } from 'pinia'
import { CartItem } from '@/types/cart'
import { ApiRes } from '@/types/data'
import useStore from '..'
const useCartStore = defineStore('card', {
  persist: true, //数据持久化存储
  // 状态
  state: () => ({
    // 购物车列表
    list: [] as CartItem[]
  }),
  // 方法
  actions: {
    async addCart(data: CartItem) {
      if (this.isLogin) {
        await request.post('/member/cart', { skuId: data.skuId, count: data.count })

        //重新获取购物车数据
        this.getCartList()
      } else {
        const goods = this.list.find((item) => item.skuId === data.skuId)
        if (goods) {
          goods.count += data.count
        } else {
          this.list.unshift(data)
        }
      }
    },
    //获取购物车数据
    async getCartList() {
      if (this.isLogin) {
        const res = await request.get<ApiRes<CartItem[]>>('/member/cart')
        this.list = res.data.result
      } else {
        console.log('获取数据')
      }
    },
    // 删除购物车数据
    async delCart(skuId: string[]) {
      if (this.isLogin) {
        await request.delete('/member/cart', {
          data: { ids: skuId }
        })
        //获取购物车数据
        this.getCartList()
      } else {
        this.list = this.list.filter((item) => !skuId.includes(item.skuId))
      }
    },
    //修改购物车数据
    async updateCart(skuId: string, data: { selected?: boolean; count?: number }) {
      if (this.isLogin) {
        await request.put(`/member/cart/${skuId}`, data)
        this.getCartList()
      } else {
        const sku = this.list.find((item) => item.skuId === skuId)!
        if (data.selected !== undefined) sku.selected = data.selected
        if (data.count !== undefined) sku.count = data.count
      }
    },
    //全选影响反选
    async updateCartAllSelected(selected: boolean) {
      if (this.isLogin) {
        await request.put('/member/cart/selected', { selected })
        this.getCartList()
      } else {
        this.list.forEach((item) => (item.selected = selected))
      }
    },
    //退出清空购物车
    clearCart() {
      this.list = []
    },
    //合并购物车
    async mergeLocalCart() {
      const data = this.list.map((item) => {
        return {
          skuId: item.skuId,
          selected: item.selected,
          count: item.count
        }
      })
      console.log(data)
      await request.post('/member/cart/merge', data)
      this.getCartList()
    }
  },
  // 计算
  getters: {
    //判断是否登录
    isLogin(): boolean {
      const { user } = useStore()
      return !!user.profile.token
      // return Boolean(user.profile.token)
    },
    //筛选商品
    effectiveList(): CartItem[] {
      return this.list.filter((item) => item.isEffective && item.stock > 0)
    },
    // 有效商品的总数量
    effectiveListCounts(): number {
      return this.effectiveList.reduce((sum, item) => sum + item.count, 0)
    },
    // 有效商品的总价格
    effectiveListPrice(): string {
      return this.effectiveList
        .reduce((sum, item) => sum + item.count * Number(item.nowPrice), 0)
        .toFixed(2)
    },
    //反选影响全选
    isAllSelected(): boolean {
      return this.effectiveList.length !== 0 && this.effectiveList.every((item) => item.selected)
    },

    //选中商品的数量
    selectedListCounts(): number {
      return this.effectiveList
        .filter((item) => item.selected)
        .reduce((sum, item) => sum + item.count, 0)
    },
    //选中商品的总价
    selectedListPrice(): string {
      return this.effectiveList
        .filter((item) => item.selected)
        .reduce((sum, item) => sum + item.count * +item.nowPrice, 0)
        .toFixed(2)
    }
  }
})

export default useCartStore
